package cn.parus.commons.utils;

import cn.parus.commons.common.Execption.CacheSerializationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @Author: Axel
 * @Description: TODO
 **/
@Component
public class ParseJsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    public ParseJsonUtil(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 字符串反序列化工具
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public <T> T parseJson(String json, Class<T> clazz) {
        if(json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new CacheSerializationException("JSON反序列化失败", e);
        }
    }

    /**
     * 列表反序列化工具
     * @param json
     * @param elementClazz
     * @return
     * @param <T>
     */
    public <T> List<T> parseJsonToList(String json, Class<T> elementClazz) {
        if (json == null) return Collections.emptyList();
        try {
            return objectMapper.readValue(json,
                    objectMapper.getTypeFactory().constructCollectionType(List.class, elementClazz));
        } catch (JsonProcessingException e) {
            throw new CacheSerializationException("列表反序列化失败", e);
        }
    }
}
